package com.party.web.web.controller.websocket;

import com.party.core.model.member.MemberGroup;
import com.party.web.utils.RealmUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Socket建立连接（握手）和断开
 * Created by wei.li
 *
 * @date 2017/4/21 0021
 * @time 9:29
 */
public class HandShake implements HandshakeInterceptor {

    Logger logger= LoggerFactory.getLogger(getClass());

    public static final String CLIENT_ID = "memberId";

    public static final String SESSION_ID = "sessionId";

    public static final String FROM_FLAG = "fromFlag";

    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                                   WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        if (serverHttpRequest instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest request = (ServletServerHttpRequest) serverHttpRequest;
            HttpSession session = request.getServletRequest().getSession();
            if (session != null) {
                Subject subject = SecurityUtils.getSubject();
                Session shiroSession = subject.getSession(false);
                if (shiroSession == null){
                    shiroSession = subject.getSession();
                }
                if (null != shiroSession){
                    MemberGroup member = RealmUtils.getCurrentUser();
                    if (null != member){
                        map.put(CLIENT_ID, member.getId());
                        map.put(SESSION_ID, session.getId());
                        map.put(FROM_FLAG, "true");
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                               WebSocketHandler webSocketHandler, Exception e) {

    }
}
